import Mn from 'backbone.marionette';
import Bb from 'backbone';
import Radio from 'backbone.radio';

import {
    scrollTop
} from 'tools.js';
import {
    hideRegion,
    showRegion
} from 'backbone-tools';
import ActionButtonCollection from 'base/models/ActionButtonCollection.js';
import ButtonCollectionWidget from 'widgets/ButtonCollectionWidget.js';
import FormBehavior from 'base/behaviors/FormBehavior.js';
import InputWidget from 'widgets/InputWidget.js';
import TextAreaWidget from 'widgets/TextAreaWidget.js';
import SelectWidget from 'widgets/SelectWidget.js';
import TvaProductFormMixin from 'base/views/TvaProductFormMixin.js';
import MessageView from 'base/views/MessageView.js';
import ErrorView from 'base/views/ErrorView.js';

import WorkItemComponent from './work_item/WorkItemComponent.js';
import StockOperationComponent from './stock/StockOperationComponent.js';
import ProductResume from './ProductResume.js';
import RadioChoiceButtonWidget from 'widgets/RadioChoiceButtonWidget.js';
import HelpTextView from './HelpTextView.js';


const ProductForm = Mn.View.extend(TvaProductFormMixin).extend({
    template: require('./templates/ProductForm.mustache'),
    behaviors: [FormBehavior],
    partial: true,
    className: 'main_content',
    regions: {
        resume: '.resume',
        messageContainer: '.message-container',
        errors: '.errors',
        type_: '.field-type_',
        label: '.field-label',
        title: ".field-title",
        description: '.field-description',
        mode: ".field-mode",
        margin_rate: '.field-margin_rate',
        ht: '.field-ht',
        ttc: '.field-ttc',
        unity: '.field-unity',
        tva_id: '.field-tva_id',
        product_id: '.field-product_id',
        supplier_id: '.field-supplier_id',
        supplier_ref: '.field-supplier_ref',
        supplier_unity_amount: '.field-supplier_unity_amount',
        supplier_ht: '.field-supplier_ht',
        stocks: '.stocks',
        items: '.items',
        category_id: '.field-category_id',
        ref: '.field-ref',
        notes: '.field-notes',
        // Training fields are now handeld in child classes
        other_buttons: {
            el: '.other_buttons',
            replaceElement: true
        },
    },
    events: {
        /*'data:invalid': 'onDataInvalid',*/
    },
    modelEvents: {
        /*'updated:ht': 'renderHT',*/
        'saved:supplier_ht': 'onAmountChange',
        'saved:margin_rate': 'onAmountChange',
        'saved:ht': 'onAmountChange',
        'saved:ttc': 'onAmountChange',
        'saved:tva_id': 'onAmountChange',
        'saved:mode': 'onModeChange',
        'change:tva_id': 'refreshTvaProductSelect',
        'change:type_': 'render', // Si on change le type_ on veut (ou pas) les stocks
        'validated:invalid': 'showErrors',
        'validated:valid': 'hideErrors',
    },
    childViewEvents: {
        'action:clicked': 'onActionClicked',
        'change:productMode': 'onModeChange',
        'show:help': 'showHelpMessage',
        'hide:help': 'hideHelpMessage',
    },
    childViewTriggers: {
        'finish': 'data:persist',
        'change': 'data:modified',
    },

    // Used to vary some labels among form inheritance
    complexTitle: "Titre du produit composé",
    descriptionHelp: "",
    descriptionTitle: "Description",

    initialize() {
        this.config = Radio.channel('config');
        this.facade = Radio.channel('facade');
        this.app = Radio.channel('app');
        this.unity_options = this.config.request(
            'get:options',
            'unities'
        );
        this.tva_mode_enabled = this.config.request('get:options', 'tva_mode_enabled');
        if (this.tva_mode_enabled) {
            this.tva_options = this.config.request(
                'get:options',
                'tvas'
            );
            // Form should have no tva by default
            this.tva_options.forEach(function (item) {
                item['default'] = false;
            });
            this.product_options = this.config.request(
                'get:options',
                'products'
            );
            this.all_product_options = this.config.request(
                'get:options',
                'products'
            );
        }

        this.supplier_options = this.config.request(
            'get:options',
            'suppliers'
        );
        this.category_options = this.facade.request(
            'get:collection',
            'categories'
        ).toJSON();
        this.work_form = false;
        this.training_form = false;
        this.ttc_mode_enabled = this.config.request('get:options', 'ttc_mode_enabled');
        const model_type = this.model.get('type_')
        // On traîte le cas des services dynamiquement car pour les types
        // simples on permet le changement de type à la volée
        if (model_type === 'sale_product_work') {
            this.work_form = true;
        } else if (['sale_product_training', 'sale_product_vae'].includes(model_type)) {
            this.training_form = true;
        }
        this.margin_rate_enabled = this.config.request('get:options', 'margin_rate_enabled');

        this.model.setupSyncEvents();
    },
    isServiceForm() {
        /* Permet de savoir si on doit afficher les stocks */
        return this.model.get('type_') == 'sale_product_service_delivery';
    },
    showMessageView() {
        var model = new Bb.Model();
        var view = new MessageView({
            model: model
        });
        this.showChildView('messageContainer', view);
    },
    renderLabel() {
        this.showChildView('label', new InputWidget({
            title: "Nom interne",
            field_name: 'label',
            value: this.model.get('label'),
            description: "Nom du produit dans le catalogue",
            required: true,
        }));
    },
    renderCategory() {
        if (this.category_options.length) {
            this.showChildView(
                'category_id',
                new SelectWidget({
                    title: "Catégorie",
                    field_name: 'category_id',
                    options: this.category_options,
                    id_key: 'id',
                    label_key: 'title',
                    value: this.model.get('category_id'),
                    placeholder: 'Choisir une catégorie',
                })
            );
        } else {
            const region = this.getRegion('category_id');
            hideRegion(region);
        }
    },
    renderInternalRef() {
        this.showChildView(
            'ref',
            new InputWidget({
                title: "Référence interne",
                field_name: 'ref',
                value: this.model.get('ref'),
            })
        );
    },
    renderSupplierHT() {
        this.showChildView(
            'supplier_ht',
            new InputWidget({
                title: "Coût d’achat HT",
                field_name: 'supplier_ht',
                value: this.model.get('supplier_ht'),
                description: "Déboursé sec du produit, utilisé pour calculer le prix de vente HT grâce au coefficients de marge et de frais généraux ainsi qu'aux différentes contributions"
            })
        );
    },
    renderHT() {
        if ((!this.work_form) && (!this.training_form)) {
            let label = "Montant HT";
            let editable = false;
            const mode = this.model.get('mode');
            let description = "";

            if (mode == 'ht') {
                editable = true;
            } else if (mode == 'supplier_ht') {
                description = "Calculé depuis le \"Coût d'achat\"";
            } else if (mode == "ttc") {
                description = "Calculé depuis le TTC avec la valeur de TVA sélectionnée";
            }
            this.showChildView('ht', new InputWidget({
                title: label,
                field_name: 'ht',
                value: this.model.get('ht'),
                editable: editable,
                description: description
            }));
        }
    },
    renderMarginRate() {
        if (this.margin_rate_enabled && this.model.get('mode') == 'supplier_ht') {
            const region = this.getRegion('margin_rate');
            showRegion(region);
            this.showChildView(
                'margin_rate',
                new InputWidget({
                    title: "Coefficient de marge",
                    field_name: 'margin_rate',
                    description: "Nombre entre 0 et 1 permettant le calcul du prix de vente depuis le coût d'achat",
                    value: this.model.get('margin_rate')
                })
            );
        } else {
            const region = this.getRegion('margin_rate');
            hideRegion(region);
        }
    },
    renderTva() {
        if (this.tva_mode_enabled) {
            this.showChildView(
                'tva_id',
                new SelectWidget({
                    title: "TVA",
                    field_name: 'tva_id',
                    options: this.tva_options,
                    id_key: 'id',
                    value: this.model.get('tva_id'),
                    placeholder: 'Choisir un taux de TVA',
                })
            );
        } else {
            const region = this.getRegion('tva_id');
            hideRegion(region);
        }
    },
    renderTTC() {
        if (this.tva_mode_enabled || this.ttc_mode_enabled) {
            if ((!this.work_form) && (!this.training_form)) {
                const label = "Montant TTC"
                const editable = this.model.get('mode') == 'ttc';
                this.showChildView('ttc', new InputWidget({
                    title: label,
                    field_name: 'ttc',
                    value: this.model.get('ttc'),
                    editable: editable
                }));
            }
        } else {
            const region = this.getRegion('ttc');
            hideRegion(region);
        }
    },
    renderProduct() {
        if (this.tva_mode_enabled) {
            this.product_options = this.getProductOptions(
                this.tva_options,
                this.all_product_options,
            );
            this.showChildView(
                'product_id',
                new SelectWidget({
                    title: "Compte produit",
                    field_name: 'product_id',
                    options: this.product_options,
                    id_key: 'id',
                    value: this.model.get('product_id'),
                    description: "Les comptes produits sont proposés après le choix de la TVA",
                    placeholder: 'Choisir un compte produit',
                })
            );
        } else {
            const region = this.getRegion('product_id');
            hideRegion(region);
        }
    },
    showCommonFields() {
        /* Section Informations internes */
        this.renderLabel();
        this.renderCategory();
        this.renderInternalRef();

        if (this.work_form || this.training_form) {
            this.showChildView(
                'type_',
                new InputWidget({
                    type: 'hidden',
                    field_name: 'type_',
                    value: this.model.get('type_')
                })
            );
        } else {
            this.showChildView(
                'type_',
                new SelectWidget({
                    field_name: "type_",
                    label: "Type de produit",
                    value: this.model.get('type_'),
                    options: this.config.request(
                        'get:options',
                        'base_product_types'
                    ),
                    label_key: 'label',
                    id_key: 'value',
                })
            );
            const modeOptions = [{
                    'label': 'HT',
                    'value': 'ht'
                },
                {
                    'label': "Coût d'achat",
                    'value': 'supplier_ht'
                },
            ]
            if (this.ttc_mode_enabled) {
                modeOptions.push({
                    'label': 'TTC',
                    'value': 'ttc'
                });
            }

            this.showChildView(
                "mode",
                new RadioChoiceButtonWidget({
                    field_name: "mode",
                    label: "Mode de calcul du prix",
                    value: this.model.get('mode'),
                    "options": modeOptions,
                })
            )
        }

        //
        this.showChildView(
            'description',
            new TextAreaWidget({
                title: this.descriptionTitle,
                description: this.descriptionDescription,
                field_name: 'description',
                value: this.model.get('description'),
                tinymce: true,
            }));
        this.showChildView(
            'unity',
            new SelectWidget({
                title: "Unité",
                field_name: 'unity',
                options: this.unity_options,
                value: this.model.get('unity'),
                placeholder: 'Choisir une unité',
            })
        );
        this.renderMarginRate();
        this.renderHT();
        this.renderTva();
        this.renderTTC();
        this.renderProduct();

        /* Section Notes */
        this.showChildView(
            'notes',
            new TextAreaWidget({
                title: "Notes",
                field_name: 'notes',
                value: this.model.get('notes')
            })
        );
    },
    showWorkFields() {
        this.showChildView(
            'title',
            new InputWidget({
                label: this.complexTitle,
                description: "Titre du chapitre ou de l’ouvrage quand le produit composé sera inséré dans le document final",
                field_name: "title",
                value: this.model.get('title'),
                required: true,
            })
        );
        /* Section Produit composé (Chapitre ou Ouvrage) */
        this.showChildView(
            'items',
            new WorkItemComponent({
                collection: this.model.items
            })
        );
    },
    showSupplierFields() {
        this.showChildView(
            'supplier_id',
            new SelectWidget({
                title: "Fournisseur",
                field_name: 'supplier_id',
                options: this.supplier_options,
                id_key: 'id',
                label_key: 'label',
                value: this.model.get('supplier_id'),
                placeholder: 'Choisir un fournisseur',
            })
        );
        this.showChildView(
            'supplier_ref',
            new InputWidget({
                title: "Référence Fournisseur",
                field_name: 'supplier_ref',
                value: this.model.get('supplier_ref'),
            })
        );
        this.showChildView(
            'supplier_unity_amount',
            new InputWidget({
                title: "Unité de vente Fournisseur",
                field_name: 'supplier_unity_amount',
                value: this.model.get('supplier_unity_amount'),
            })
        );
        this.renderSupplierHT();
    },
    showStockFields() {
        this.showChildView(
            'stocks',
            new StockOperationComponent({
                collection: this.model.stock_operations
            })
        );
    },
    showOtherActionButtons() {
        let collection = new ActionButtonCollection();
        let buttons = [{
            label: 'Dupliquer',
            action: 'duplicate',
            icon: 'copy',
            showLabel: false
        }];
        if (!this.model.get('locked')) {
            buttons.push({
                label: "Supprimer",
                action: "delete",
                icon: "trash-alt",
                showLabel: false,
                css: 'negative'
            });
        }
        collection.add(buttons);
        let view = new ButtonCollectionWidget({
            collection: collection
        });
        this.showChildView('other_buttons', view);
    },
    templateContext() {
        const result = {
            is_training: (this.model.get('type_') === 'sale_product_training'),
            complex: this.work_form || this.training_form,
            work_form: this.work_form,
            service_form: this.isServiceForm(),
            training_form: this.training_form,
            margin_rate: this.margin_rate_enabled
        };
        return result;
    },
    onRender() {
        this.showMessageView();
        this.showCommonFields();
        if ((!this.work_form) && (!this.training_form)) {
            this.showSupplierFields();
        }
        if (this.work_form || this.training_form) {
            this.showWorkFields();
        }
        // Le champ type_ peut changer en cours de route pour les produits
        // simples on utilise donc une méthode plutôt qu'un attribut
        if (!this.isServiceForm()) {
            this.showStockFields();
        }
        this.showChildView(
            'resume',
            new ProductResume({
                model: this.model
            })
        );
        this.showOtherActionButtons();
    },
    onAttach() {
        scrollTop();
    },
    renderAmounts() {
        this.renderHT();
        this.renderSupplierHT();
        this.renderTTC();
    },
    onAmountChange(key, value) {
        this.renderAmounts();
    },
    onModeChange(key, value) {
        this.renderMarginRate();
        this.renderAmounts();
    },
    onActionClicked(actionName) {
        console.log("Action clicked : %s", actionName);
        this.app.trigger("product:" + actionName, this);
    },
    onFormSubmitted() {
        this.app.trigger('navigate', 'index');
    },
    onCancelForm() {
        this.app.trigger('navigate', 'index');
    },
    onDataInvalid(model, errors) {
        console.log("ProductForm.onInvalid");
        this.showChildView('errors', new ErrorView({
            errors: errors
        }));
    },
    showHelpMessage() {
        this.showChildView(
            "messageContainer",
            new HelpTextView({
                model: this.model
            }));
    },
    hideHelpMessage() {
        this.getRegion('messageContainer').empty();
    }
});
export default ProductForm
